package com.ddl.controller.core;

import com.ddl.common.enums.ResultType;
import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.pay.MchOrderInfoResult;
import com.ddl.pay.WeChatPayDto;
import com.ddl.pay.XMLUtil;
import com.ddl.pojo.PayFlowWithBLOBs;
import com.ddl.service.IUserPayService;
import com.ddl.util.DataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2019/1/22
 */
@RestController
@RequestMapping(value = "/app/pay")
public class PayController {
    private final static Logger logger = LoggerFactory.getLogger(PayController.class);


    @Autowired
    IUserPayService iUserPayService;

    /**
     * 微信支付
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/weixinPay")
    public ResultModel weixinPay(@RequestBody Map<String,Object> map, HttpServletRequest request) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try{
            String ip= DataUtil.getIpAdrress(request);
            String userId=request.getHeader("userId");
            WeChatPayDto weChatPayDto=iUserPayService.WeChatPay(map.get("orderId").toString(),ip,new BigDecimal(map.get("amount").toString()),userId);
            resultModel.setData(weChatPayDto);
        }catch (Exception e){
            logger.error("weixinPay fail", e);
            resultModel= ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 微信支付
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
        @RequestMapping(value = "/weixinQuery")
    public ResultModel weixinQuery(@RequestBody Map<String,Object> map, HttpServletRequest request) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try{
            MchOrderInfoResult weChatPayDto=iUserPayService.weixinQuery(map.get("orderId").toString());
            resultModel.setData(weChatPayDto);
        }catch (Exception e){
            logger.error("weixinQuery fail", e);
            resultModel= ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 执行回调 确认支付后处理事件 例如添加金额到数据库等操作
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/payNotify.do")
    public void weixin_notify(HttpServletRequest request, HttpServletResponse response)throws Exception {

        System.out.println("进入支付h5回调=====================");
        String xmlMsg = readData(request);
        System.out.println("pay notice---------"+xmlMsg);
        Map params = XMLUtil.doXMLParse(xmlMsg);
        String result_code  = params.get("result_code")+"";
        String attach      = params.get("attach")+"";
        String userid = null;
        try {
            // 过滤空 设置 TreeMap
            SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
            Iterator it = params.keySet().iterator();
            while (it.hasNext()) {
                String parameter = (String) it.next();
                String parameterValue = params.get(parameter)+"";
                String v = "";
                if (null != parameterValue) {
                    v = parameterValue.trim();
                }
                System.out.println("value==============="+v);
                packageParams.put(parameter, v);
            }
            // 查看回调参数
            // LogUtil.writeMsgToFile(packageParams.toString());
            BigDecimal total_fee = new BigDecimal((String) packageParams.get("total_fee")).divide(new BigDecimal(100));
            // 账号信息
            String resXml = "";
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            String code = (String)packageParams.get("result_code");
            if ("SUCCESS".equals(code)) {
                // 这里是支付成功
                PayFlowWithBLOBs shoppingPayFlow = new  PayFlowWithBLOBs();
                shoppingPayFlow.setOrderId(packageParams.get("out_trade_no").toString());
                shoppingPayFlow.setAmount(total_fee);
                shoppingPayFlow.setDealStatus(ResultType.SUCCESS.getCode());
                iUserPayService.paySuccess(shoppingPayFlow);
                ////////// 执行自己的业务逻辑////////////////
                // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[充值失败]]></return_msg>" + "</xml> ";
            }
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error("weixin_notify异常{}",e);
        }
    }
    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line=br.readLine())!=null;) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }

            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            if (br != null)
                try {br.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
}
